<template>
    <div class="glass-background min-h-screen flex items-center justify-center font-sans text-glass-text">
        <div class="w-full max-w-md">
            <!-- Logo 区域 -->
            <div class="text-center mb-8">
                <div class="w-16 h-16 glass-card rounded-full flex items-center justify-center mx-auto mb-4">
                    <i class="fas fa-robot text-glass-primary text-2xl"></i>
                </div>
                <h1 class="text-3xl font-bold text-glass-text mb-2">AI Chat</h1>
                <p class="text-glass-text-muted">智能对话助手</p>
            </div>

            <!-- 登录表单 -->
            <div class="login-container rounded-xl shadow-lg p-8">
                <h2 class="text-2xl font-semibold text-glass-text mb-6 text-center">登录您的账户</h2>

                <!-- 错误提示 -->
                <div v-if="errorMessage" class="mb-4 p-3 bg-red-100 border border-red-400 text-red-700 rounded-lg">
                    <i class="fas fa-exclamation-triangle mr-2"></i>
                    {{ errorMessage }}
                </div>

                <!-- 成功提示 -->
                <div v-if="successMessage"
                    class="mb-4 p-3 bg-green-100 border border-green-400 text-green-700 rounded-lg">
                    <i class="fas fa-check-circle mr-2"></i>
                    {{ successMessage }}
                </div>

                <form @submit.prevent="handleLogin" class="space-y-6">
                    <!-- 用户名输入 -->
                    <div>
                        <label for="username" class="block text-sm font-medium text-glass-text mb-2">用户名</label>
                        <div class="relative">
                            <input type="text" id="username" name="username" required v-model="loginForm.username"
                                :disabled="isLoading"
                                class="glass-input w-full px-4 py-3 rounded-lg outline-none transition-all duration-200 text-glass-text placeholder-glass-text-muted disabled:bg-gray-100 disabled:cursor-not-allowed"
                                placeholder="请输入您的用户名" @blur="validateUsername">
                            <i
                                class="fas fa-user absolute right-3 top-1/2 transform -translate-y-1/2 text-glass-text-muted"></i>
                        </div>
                        <p v-if="usernameError" class="text-red-500 text-sm mt-1">{{ usernameError }}</p>
                    </div>

                    <!-- 密码输入 -->
                    <div>
                        <label for="password" class="block text-sm font-medium text-glass-text mb-2">密码</label>
                        <div class="relative">
                            <input :type="showPassword ? 'text' : 'password'" id="password" name="password" required
                                v-model="loginForm.password" :disabled="isLoading"
                                class="glass-input w-full px-4 py-3 rounded-lg outline-none transition-all duration-200 text-glass-text placeholder-glass-text-muted disabled:bg-gray-100 disabled:cursor-not-allowed"
                                placeholder="请输入您的密码" @blur="validatePassword">
                            <i class="fas fa-lock absolute right-3 top-1/2 transform -translate-y-1/2 text-glass-text-muted"></i>
                        </div>
                        <p v-if="passwordError" class="text-red-500 text-sm mt-1">{{ passwordError }}</p>
                    </div>

                    <!-- 记住我和忘记密码 -->
                    <div class="flex items-center justify-between">
                        <label class="flex items-center">
                            <input type="checkbox" v-model="loginForm.remember" :disabled="isLoading"
                                class="w-4 h-4 text-glass-text bg-glass-bg border-glass-border rounded focus:ring-glass-primary disabled:cursor-not-allowed">
                            <span class="ml-2 text-sm text-glass-text-muted">记住我</span>
                        </label>
                        <button type="button" @click="handleForgotPassword" :disabled="isLoading"
                            class="text-sm text-glass-text hover:text-glass-primary transition-colors disabled:text-gray-400 disabled:cursor-not-allowed">
                            忘记密码？
                        </button>
                    </div>

                    <!-- 登录按钮 -->
                    <button type="submit" :disabled="isLoading || !isFormValid"
                        class="glass-button w-full text-glass-text font-semibold py-3 px-4 rounded-lg transition-all duration-200 disabled:bg-gray-400 disabled:cursor-not-allowed">
                        <i v-if="isLoading" class="fas fa-spinner fa-spin mr-2"></i>
                        <i v-else class="fas fa-sign-in-alt mr-2"></i>
                        {{ isLoading ? '登录中...' : '登录' }}
                    </button>

                    <!-- 分割线 -->
                    <div class="relative my-6">
                        <div class="absolute inset-0 flex items-center">
                            <div class="w-full border-t border-glass-border"></div>
                        </div>
                        <div class="relative flex justify-center text-sm">
                            <span class="px-2 bg-transparent text-glass-text-muted">或者</span>
                        </div>
                    </div>

                    <!-- 第三方登录 -->
                    <div class="space-y-3">
                        <button type="button" @click="handleOAuthLogin('google')" :disabled="isLoading"
                            class="glass-button w-full flex items-center justify-center px-4 py-3 rounded-lg transition-colors text-glass-text disabled:bg-gray-100 disabled:cursor-not-allowed">
                            <svg class="w-5 h-5 mr-3" viewBox="0 0 24 24">
                                <path fill="#4285F4"
                                    d="M22.56 12.25c0-.78-.07-1.53-.2-2.25H12v4.26h5.92c-.26 1.37-1.04 2.53-2.21 3.31v2.77h3.57c2.08-1.92 3.28-4.74 3.28-8.09z" />
                                <path fill="#34A853"
                                    d="M12 23c2.97 0 5.46-.98 7.28-2.66l-3.57-2.77c-.98.66-2.23 1.06-3.71 1.06-2.86 0-5.29-1.93-6.16-4.53H2.18v2.84C3.99 20.53 7.7 23 12 23z" />
                                <path fill="#FBBC05"
                                    d="M5.84 14.09c-.22-.66-.35-1.36-.35-2.09s.13-1.43.35-2.09V7.07H2.18C1.43 8.55 1 10.22 1 12s.43 3.45 1.18 4.93l2.85-2.22.81-.62z" />
                                <path fill="#EA4335"
                                    d="M12 5.38c1.62 0 3.06.56 4.21 1.64l3.15-3.15C17.45 2.09 14.97 1 12 1 7.7 1 3.99 3.47 2.18 7.07l3.66 2.84c.87-2.6 3.3-4.53 6.16-4.53z" />
                            </svg>
                            使用 Google 登录
                        </button>

                        <button type="button" @click="handleOAuthLogin('microsoft')" :disabled="isLoading"
                            class="glass-button w-full flex items-center justify-center px-4 py-3 rounded-lg transition-colors text-glass-text disabled:bg-gray-100 disabled:cursor-not-allowed">
                            <i class="fab fa-microsoft text-blue-600 text-lg mr-3"></i>
                            使用 Microsoft 登录
                        </button>
                    </div>

                    <!-- 注册链接 -->
                    <div class="text-center mt-6">
                        <p class="text-sm text-glass-text-muted">
                            还没有账户？
                            <router-link to="/register"
                                class="text-glass-text hover:text-glass-primary font-medium transition-colors">
                                立即注册
                            </router-link>
                        </p>
                    </div>
                </form>
            </div>

            <!-- 底部信息 -->
            <div class="text-center mt-8 text-sm text-glass-text-muted">
                <p>© 2024 AI Chat. 保留所有权利.</p>
                <div class="mt-2 space-x-4">
                    <a href="#" class="hover:text-glass-text transition-colors">服务条款</a>
                    <a href="#" class="hover:text-glass-text transition-colors">隐私政策</a>
                    <a href="#" class="hover:text-glass-text transition-colors">帮助</a>
                </div>
            </div>
        </div>

        <!-- 忘记密码弹窗 -->
        <div v-if="showForgotModal" class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50"
            @click="closeForgotModal">
            <div class="bg-white rounded-lg p-6 w-full max-w-md mx-4" @click.stop>
                <div class="flex justify-between items-center mb-4">
                    <h3 class="text-lg font-semibold text-gray-800">重置密码</h3>
                    <button @click="closeForgotModal" class="text-gray-400 hover:text-gray-600">
                        <i class="fas fa-times"></i>
                    </button>
                </div>

                <form @submit.prevent="handleResetPassword">
                    <div class="mb-4">
                        <label class="block text-sm font-medium text-gray-700 mb-2">邮箱地址</label>
                        <input type="email" v-model="resetEmail" required
                            class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-emerald-500 focus:border-transparent outline-none"
                            placeholder="请输入您的邮箱地址">
                    </div>

                    <div class="flex space-x-3">
                        <button type="button" @click="closeForgotModal"
                            class="flex-1 px-4 py-2 border border-gray-300 text-gray-700 rounded-lg hover:bg-gray-50 transition-colors">
                            取消
                        </button>
                        <button type="submit" :disabled="isSendingReset"
                            class="flex-1 px-4 py-2 bg-emerald-600 text-white rounded-lg hover:bg-emerald-700 disabled:bg-gray-400 transition-colors">
                            <i v-if="isSendingReset" class="fas fa-spinner fa-spin mr-2"></i>
                            {{ isSendingReset ? '发送中...' : '发送重置邮件' }}
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { loginAPI, forgotPasswordAPI, getOauthUrlAPI, type LoginRequest } from '@/http/chatAPI'
import { useUserStore } from '@/stores/user'
import { getTokenExpiry } from '@/utils/tokenManager'

const router = useRouter()
const userStore = useUserStore()

// 响应式数据
const isLoading = ref(false)
const showPassword = ref(false)
const errorMessage = ref('')
const successMessage = ref('')
const usernameError = ref('')
const passwordError = ref('')
const showForgotModal = ref(false)
const resetEmail = ref('')
const isSendingReset = ref(false)

// 登录表单数据
const loginForm = ref<LoginRequest>({
    username: '',
    password: '',
    remember: false
})

// 计算属性
const isFormValid = computed(() => {
    return loginForm.value.username &&
        loginForm.value.password &&
        !usernameError.value &&
        !passwordError.value
})

// 用户名验证
const validateUsername = () => {
    if (!loginForm.value.username) {
        usernameError.value = '请输入用户名'
    } else if (loginForm.value.username.length < 2) {
        usernameError.value = '用户名至少2个字符'
    } else if (loginForm.value.username.length > 20) {
        usernameError.value = '用户名不能超过20个字符'
    } else if (!/^[a-zA-Z0-9_\u4e00-\u9fa5]+$/.test(loginForm.value.username)) {
        usernameError.value = '用户名只能包含字母、数字、下划线和中文'
    } else {
        usernameError.value = ''
    }
}

// 密码验证
const validatePassword = () => {
    if (!loginForm.value.password) {
        passwordError.value = '请输入密码'
    } else if (loginForm.value.password.length < 6) {
        passwordError.value = '密码长度至少6位'
    } else {
        passwordError.value = ''
    }
}

// 切换密码可见性
const togglePasswordVisibility = () => {
    showPassword.value = !showPassword.value
}

// 清除消息
const clearMessages = () => {
    errorMessage.value = ''
    successMessage.value = ''
}

// 处理登录
const handleLogin = async () => {
    clearMessages()

    // 验证表单
    validateUsername()
    validatePassword()

    if (!isFormValid.value) {
        return
    }

    isLoading.value = true

    try {
        const response = await loginAPI(loginForm.value)

        // 使用store管理用户状态，根据"记住我"设置token过期时间
        const expiryHours = getTokenExpiry(loginForm.value.remember)
        userStore.login(response.token, response.user, expiryHours)

        successMessage.value = '登录成功！正在跳转...'

        // 延迟跳转以显示成功消息
        setTimeout(() => {
            router.push('/')
        }, 1500)

    } catch (error: any) {
        errorMessage.value = error.message || '登录失败，请重试'
    } finally {
        isLoading.value = false
    }
}

// 处理第三方登录
const handleOAuthLogin = async (provider: string) => {
    try {
        isLoading.value = true
        const response = await getOauthUrlAPI(provider, window.location.origin + '/auth/callback')
        window.location.href = response.url
    } catch (error: any) {
        errorMessage.value = error.message || `${provider} 登录失败`
        isLoading.value = false
    }
}

// 处理忘记密码
const handleForgotPassword = () => {
    resetEmail.value = ''
    showForgotModal.value = true
}

// 关闭忘记密码弹窗
const closeForgotModal = () => {
    showForgotModal.value = false
    resetEmail.value = ''
}

// 处理重置密码
const handleResetPassword = async () => {
    if (!resetEmail.value) {
        return
    }

    isSendingReset.value = true

    try {
        await forgotPasswordAPI(resetEmail.value)
        successMessage.value = '重置邮件已发送，请查收邮箱'
        closeForgotModal()
    } catch (error: any) {
        errorMessage.value = error.message || '发送重置邮件失败'
    } finally {
        isSendingReset.value = false
    }
}

// 检查是否已登录
onMounted(() => {
    if (userStore.isAuthenticated) {
        router.push('/')
    }
})
</script>

<style scoped>
/* 自定义样式 */
.font-sans {
    font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen', 'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue', sans-serif;
}

/* 毛玻璃效果样式 */
.glass-background {
    background: linear-gradient(135deg, #f0f2f5 0%, #ffffff 50%, #f8f9fa 100%);
    min-height: 100vh;
}

.glass-effect {
    background: rgba(255, 255, 255, 0.8);
    backdrop-filter: blur(20px);
    border: 1px solid rgba(0, 0, 0, 0.08);
    box-shadow: 0 4px 16px rgba(0, 0, 0, 0.1);
}

.glass-card {
    background: linear-gradient(135deg, rgba(255, 255, 255, 0.9) 0%, rgba(255, 255, 255, 0.7) 100%);
    backdrop-filter: blur(20px);
    border: 1px solid rgba(0, 0, 0, 0.08);
    box-shadow: 0 4px 16px rgba(0, 0, 0, 0.1);
}

.glass-button {
    background: rgba(255, 255, 255, 0.8);
    backdrop-filter: blur(10px);
    border: 1px solid rgba(0, 0, 0, 0.1);
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
    transition: all 0.3s ease;
}

.glass-button:hover:not(:disabled) {
    background: rgba(255, 255, 255, 0.95);
    transform: translateY(-2px);
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.glass-input {
    background: rgba(255, 255, 255, 0.8);
    backdrop-filter: blur(10px);
    border: 1px solid rgba(0, 0, 0, 0.1);
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.glass-input:focus {
    background: rgba(255, 255, 255, 0.95);
    border-color: rgba(0, 0, 0, 0.2);
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.login-container {
    background: linear-gradient(135deg, rgba(255, 255, 255, 0.9) 0%, rgba(255, 255, 255, 0.8) 100%);
    backdrop-filter: blur(30px);
    border: 1px solid rgba(0, 0, 0, 0.08);
    box-shadow: 0 8px 24px rgba(0, 0, 0, 0.1);
}

/* 颜色变量 */
:root {
    --glass-light: #ffffff;
    --glass-light-secondary: #f8f9fa;
    --glass-dark: #1a1a1a;
    --glass-border: rgba(0, 0, 0, 0.08);
    --glass-primary: #000000;
    --glass-primary-hover: rgba(0, 0, 0, 0.8);
    --glass-secondary: #ffffff;
    --glass-text: #1f2937;
    --glass-text-muted: rgba(31, 41, 55, 0.7);
    --glass-bg: rgba(255, 255, 255, 0.7);
    --glass-bg-hover: rgba(255, 255, 255, 0.9);
    --glass-shadow: rgba(0, 0, 0, 0.1);
}

/* Tailwind自定义颜色类 */
.text-glass-primary { color: var(--glass-primary); }
.text-glass-text { color: var(--glass-text); }
.text-glass-text-muted { color: var(--glass-text-muted); }
.bg-glass-bg { background-color: var(--glass-bg); }
.border-glass-border { border-color: var(--glass-border); }
.focus\:ring-glass-primary:focus { --tw-ring-color: var(--glass-primary); }
.hover\:text-glass-primary:hover { color: var(--glass-primary); }
.placeholder-glass-text-muted::placeholder { color: var(--glass-text-muted); }

/* 输入框聚焦效果 */
input:focus {
    box-shadow: 0 0 0 3px rgba(0, 0, 0, 0.1);
}

/* 按钮悬停效果 */
button:hover:not(:disabled) {
    transform: translateY(-1px);
}

/* 加载动画 */
@keyframes spin {
    from {
        transform: rotate(0deg);
    }

    to {
        transform: rotate(360deg);
    }
}

.fa-spin {
    animation: spin 1s linear infinite;
}

/* 响应式设计 */
@media (max-width: 640px) {
    .max-w-md {
        margin: 1rem;
    }
}
</style>
